<template>
  <div class="page">
    <!-- 顶部操作按钮 -->
    <el-form :inline="true" :model="queryParams">
      <el-form-item>
        <el-button type="primary" :icon="Plus" @click="add"> 新增 </el-button>
      </el-form-item>

      <el-form-item label="单号">
        <el-input placeholder="请输入单号" v-model="queryParams.oid"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="Search"> 查询 </el-button>
      </el-form-item>
    </el-form>
    <!-- 任务列表 -->
    <el-table :data="data" :border="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="时间" prop="timeRange">
        <template #default="scope">
          <div class="column">
            <span>开始时间：{{ parseTime(scope.row.timeRange[0]) }}</span>
            <span>结束时间：{{ parseTime(scope.row.timeRange[1]) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="timeRange">
        <template #default="scope">
          <el-button type="danger" size="mini" @click="del(scope.$index)">删除</el-button>
          <el-button type="primary" size="mini" @click="edit(scope.$index)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 下一轮倒计时 -->

    <div class="bottom">
      <span v-if="runStatus">下一轮任务倒计时：{{ seconds }}秒</span>
      <span v-else>已暂停</span>

      <div>
        <el-button type="danger" @click="stopRun">暂停</el-button>
        <el-button type="primary" @click="run">手动执行</el-button>
      </div>
    </div>

    <!-- 表单区 -->
    <el-dialog v-model="dialogFormVisible" title="添加任务">
      <el-form :model="form">
        <el-form-item>
          <el-button type="primary" @click="pushId">添加</el-button>
        </el-form-item>
        <!-- id -->
        <el-form-item
          label="ID"
          v-for="(item, index) in form.id"
          :key="item"
          :label-width="formLabelWidth"
        >
          <el-tag class="ml-2" closable @close="handleClose(index)">{{ item }}</el-tag>
        </el-form-item>
        <!-- 时间范围 -->
        <el-form-item label="时间范围" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            format="YYYY/MM/DD HH"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="x"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save"> 保存数据 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { Plus, Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const queryParams = reactive({
  oid: ''
})

const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const mode = ref('add')
const editIndex = ref(-1)

const handleClose = (index) => {
  form.id.splice(index, 1)
}

const add = () => {
  dialogFormVisible.value = true
  mode.value = 'add'
}

const del = async (index) => {
  data.value.splice(index, 1)
  window['electron'].ipcRenderer.invoke('save', JSON.stringify(data.value))
}

const edit = async (index) => {
  dialogFormVisible.value = true
  editIndex.value = index
  mode.value = 'edit'

  form.id = data.value[index].id
  form.timeRange = data.value[index].timeRange
}

const pushId = () => {
  ElMessageBox.prompt('请输入id', 'Tip', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel'
  })
    .then(({ value }) => {
      form.id.push(value)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const save = async () => {
  let item = JSON.parse(JSON.stringify(form))

  if (mode.value === 'add') {
    data.value = [...data.value, item]
  } else {
    data.value[editIndex.value] = item
  }

  // 保存id到待执行列表
  window['electron'].ipcRenderer.invoke('save', JSON.stringify(data.value))

  dialogFormVisible.value = false

  form.id = []
}

const data = ref([])

const parseTime = (value) => {
  return dayjs(value).format('YYYY-MM-DD HH')
}

const initData = async () => {
  data.value = JSON.parse(await window['electron'].ipcRenderer.invoke('init-data'))
}

// 新增表单
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
  id: [],
  timeRange: ''
})

const running = ref(false)

const run = () => {
  running.value = true
  runStatus.value = true
  seconds.value = 30
  window['electron'].ipcRenderer.invoke('run', JSON.parse(JSON.stringify(multipleSelection.value)))
}

const stopRun = () => {
  running.value = false
  runStatus.value = false
  seconds.value = 30
}

const interval = ref(null)
const seconds = ref(30)
const runStatus = ref(true)

/**
 * 页面加载完成时获取数据
 */
onMounted(() => {
  initData()

  interval.value = setInterval(async () => {
    if (runStatus.value) {
      seconds.value = seconds.value - 1
      if (seconds.value <= 0) {
        seconds.value = 30
        running.value = true
        await initData()
        window['electron'].ipcRenderer.invoke('run', JSON.parse(JSON.stringify(data.value)))
      }
    }
  }, 1000)
})

onUnmounted(() => {
  clearInterval(interval.value)
})
</script>
<style lang="scss" scoped>
.page {
  flex: 1;
  width: 100vw;
  min-height: 100vh;
  background-color: #f7f7f7;

  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: center;
  box-sizing: border-box;

  padding: 30px;
  padding-bottom: 50px;

  .list {
    width: 100%;
  }
}

.column {
  width: 100%;
  height: 60px;
  line-height: 30rpx;

  display: flex;
  flex-flow: column nowrap;
  justify-content: space-around;
  align-items: center;
}

.bottom {
  width: 100vw;
  height: 50px;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;

  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;

  box-sizing: border-box;
  padding: 0 24px;
}
</style>
